package com.delayqueue.core.common;

import com.alibaba.fastjson.JSON;
import com.delayqueue.common.task.Task;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
public class FileUtil {


    public static HashSet<String> loadContentFromFile(File file) {
        if (file == null || !file.exists()) {
            return new HashSet<>(0);
        }
        HashSet<String> resultList = new HashSet<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));) {
            String readLine = reader.readLine();
            while (StringUtil.isNotEmpty(readLine)) {
                resultList.add(readLine);
                readLine = reader.readLine();
            }
            return resultList;
        } catch (IOException e) {
            log.error("出错了：", e);
            return new HashSet<>(0);
        }
    }

    public static HashSet<Task> loadTaskListFromFile(File file) {
        if (file == null || !file.exists()) {
            return new HashSet<>(0);
        }
        HashSet<Task> resultList = new HashSet<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
            ;
            String readLine = reader.readLine();
            while (StringUtil.isNotEmpty(readLine)) {
                Task task = JSON.parseObject(readLine, Task.class);
                resultList.add(task);
                readLine = reader.readLine();
            }
            return resultList;
        } catch (IOException e) {
            log.error("出错了：", e);
            return new HashSet<>(0);
        }
    }

    public static File[] getFileList(String dir) {
        File file = new File(dir);
        if (!file.exists()) {
            return new File[]{};
        }
        return file.listFiles();
    }

    public static boolean createFileIfNotExisis(File file) {
        if (!file.exists()) {
            String dirPath = file.getParentFile().getPath();
            File dir = new File(dirPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            try {
                boolean result = file.createNewFile();
                return result;
            } catch (IOException e) {
                log.error("出错了：", e);
                return false;
            }
        }
        return false;
    }

    /**
     * 清除文件内容
     *
     * @param file
     */
    public static void clearFile(File file) {
        if (file != null && file.exists()) {
            try (FileWriter writer = new FileWriter(file)) {
                writer.write("");
                writer.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 从目标文件结尾追加
     *
     * @param source
     * @param target
     */
    public static void copyData(File source, File target) {

        if (source == null || !source.exists()) {
            return;
        }
        HashSet<Task> dataList = loadTaskListFromFile(source);
        if (!dataList.isEmpty()) {
            createFileIfNotExisis(target);
            try (FileOutputStream fout = new FileOutputStream(target, true)) {
                Iterator<Task> iterator = dataList.iterator();
                Charset charset = StandardCharsets.UTF_8;
                while (iterator.hasNext()) {
                    fout.write((JSON.toJSONString(iterator.next()) + "\r\n").getBytes(charset));
                }
            } catch (IOException e) {
                log.error("出错了：", e);
            }
        }
    }


    /**
     * 根据文件目录获取按创建时间升序排序的文件列表
     *
     * @param dir 文件目录
     * @return
     */
    public static List<File> getFileListSortByCreateTime(String dir) {
        File[] files = getFileList(dir);
        return getFileListSortByCreateTime(files);
    }

    /**
     * 获取按创建时间升序排序的文件列表
     *
     * @param files 文件列表
     * @return
     */
    public static List<File> getFileListSortByCreateTime(File[] files) {
        if (files == null) {
            return null;
        }
        if (files.length == 0) {
            return new ArrayList<>(0);
        }
        List<File> result = Arrays.stream(files).sorted((o1, o2) -> {
            try {
                BasicFileAttributes att1 = Files.readAttributes(Paths.get(o1.getAbsolutePath()), BasicFileAttributes.class);
                BasicFileAttributes att2 = Files.readAttributes(Paths.get(o2.getAbsolutePath()), BasicFileAttributes.class);
                long time1 = att1.creationTime().toMillis();
                long time2 = att2.creationTime().toMillis();
                return (int) (time1 - time2);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return 0;
        }).collect(Collectors.toList());
        return result;
    }
}
